package com.ncmmall.mall.controller.business.marketing;

import com.ncmmall.application.business.goods.SubjectApplication;
import com.ncmmall.application.securitys.logs.OperationLogApplication;
import com.feijin.commons.webs.Webs;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.business.goods.channel.GoodsChannel;
import com.ncmmall.domain.business.goods.channel.QGoodsChannel;
import com.ncmmall.domain.business.goods.subject.QSubject;
import com.ncmmall.domain.business.goods.subject.Subject;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 专题
 *
 * @author likaikai
 * @date 2019-07-16 16:00
 */
@Controller
@RequestMapping("/mall/subject")
public class SubjectController {

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private SubjectApplication subjectApplication;

    @Autowired
    private OperationLogApplication logApplication;

    private Logger logger = LoggerFactory.getLogger(SubjectController.class);

    /**
     * 专题列表
     *
     * @param model
     * @param pageParams
     * @param params
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model, PageParams pageParams, Subject params) {
        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo()).setPageSize(pageParams.getPageSize());

        Map<String, Object> map = new HashMap<>();
        String sql = buildSql("select * from mall_subject where 1 = 1", map, params);

        QueryPage<Subject> page = queryChannelService.queryPageEntity(sql, pageRequest.setParams(map), Subject.class);

        model.addAttribute("params", params);
        model.addAttribute("page", page);

        return "mall/goods/subject/list";
    }

    /**
     * 条件查询
     *
     * @param sql
     * @param map
     * @param params
     * @return
     */
    private String buildSql(String sql, Map<String, Object> map, Subject params) {

        sql += " and platformType = :type ";
        map.put("type", params.getPlatformType());

        if (StringUtils.isNotBlank(params.getName())) {
            sql += " and name like :name";
            map.put("name", "%" + params.getName() + "%");
        }

        if (params.getStatus() > 0) {
            sql += " and status = :status";
            map.put("status", params.getStatus());
        }

        sql += " order by rank asc, createTime desc";

        return sql;
    }


    /**
     * 创建专题
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(Model model) {
        model.addAttribute("_method", "POST");
        model.addAttribute("subject", new Subject());
        return "mall/goods/subject/form";
    }


    /**
     * 创建专题
     *
     * @param subject
     * @param request
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> create(@RequestHeader("X-Requested-With") String requestWith, Subject subject, HttpServletRequest request) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }
            int count = queryChannelService.selectCount("select count(*) from mall_subject where name = :name", ImmutableMap.of("name", subject.getName()));
            if (count > 0) {
                return ImmutableMap.of("status", false, "message", "专题名称已存在");
            }

            subject.getGoodsSubjects().removeIf(item -> item.getGoods() == null);
            subjectApplication.create(subject);
            logApplication.eventOfSystem(Securitys.currentUser(), "添加专题", Securitys.getIp(request));
            return ImmutableMap.of("status", true);
        } catch (Exception e) {
            logger.error("[创建专题异常]", e);
            return ImmutableMap.of("status", false, "message", "创建专题异常");
        }
    }


    /**
     * 编辑专题
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/modify", method = RequestMethod.GET)
    public String modify(Model model, long id) {
        model.addAttribute("_method", "PUT");
        model.addAttribute("subject", queryChannelService.findOne(QSubject.subject.id.eq(id), Subject.class));
        return "mall/goods/subject/form";
    }


    /**
     * 编辑专题
     *
     * @param params
     * @return
     */
    @RequestMapping(value = "/modify", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> modify(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, Subject params) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            Subject subject = queryChannelService.findOne(QSubject.subject.id.eq(params.getId()), Subject.class);
            if (subject == null) {
                return ImmutableMap.of("status", false, "message", "专题不存在");
            }
            subjectApplication.modify(subject, params);
            logApplication.eventOfSystem(Securitys.currentUser(), "编辑专题", Securitys.getIp(request));
            return ImmutableMap.of("status", true);
        } catch (Exception e) {
            logger.error("[编辑专题异常]", e);
            return ImmutableMap.of("status", false, "message", "编辑专题异常");
        }
    }


    /**
     * 启用
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/enable", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> enable(@RequestHeader("X-Requested-With") String requestWith, long id) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            Subject subject = queryChannelService.findOne(QSubject.subject.id.eq(id), Subject.class);
            if (subject == null) {
                return ImmutableMap.of("status", false, "message", "专题不存在");
            }
            subjectApplication.enable(subject);
            return ImmutableMap.of("status", true);
        } catch (Exception e) {
            logger.error("[启用专题异常]", e);
            return ImmutableMap.of("status", false, "message", "启用专题异常");
        }
    }

    /**
     * 禁用
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/disable", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> disable(@RequestHeader("X-Requested-With") String requestWith, long id) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            Subject subject = queryChannelService.findOne(QSubject.subject.id.eq(id), Subject.class);
            if (subject == null) {
                return ImmutableMap.of("status", false, "message", "专题不存在");
            }
            subjectApplication.disable(subject);
            return ImmutableMap.of("status", true);
        } catch (Exception e) {
            logger.error("[禁用专题异常]", e);
            return ImmutableMap.of("status", false, "message", "禁用专题异常");
        }
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/remove", method = RequestMethod.DELETE)
    @ResponseBody
    public Map<String, Object> remove(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, long id) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            Subject subject = queryChannelService.findOne(QSubject.subject.id.eq(id), Subject.class);
            if (subject == null) {
                return ImmutableMap.of("status", false, "message", "专题不存在");
            }
            subjectApplication.remove(subject);
            logApplication.eventOfSystem(Securitys.currentUser(), "删除专题", Securitys.getIp(request));
            return ImmutableMap.of("status", true);
        } catch (Exception e) {
            logger.error("[删除专题异常]", e);
            return ImmutableMap.of("status", false, "message", "删除专题异常");
        }
    }


    /**
     * 批量下架专题
     *
     * @param requestWith
     * @param news
     * @return
     */
    @RequestMapping(value = "/disables", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> disables(@RequestHeader("X-Requested-With") String requestWith, String data) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            subjectApplication.disables(data);
            return ImmutableMap.of("status", true, "message", "下架成功");

        } catch (Exception e) {

            logger.error("专题批量下架异常", e);
            return ImmutableMap.of("status", false, "message", "下架异常");

        }
    }


    /**
     * 批量上架专题
     *
     * @param requestWith
     * @param news
     * @return
     */
    @RequestMapping(value = "/enables", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> enables(@RequestHeader("X-Requested-With") String requestWith, String data) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            subjectApplication.enables(data);
            return ImmutableMap.of("status", true, "message", "上架成功");

        } catch (Exception e) {

            logger.error("专题批量上架异常", e);
            return ImmutableMap.of("status", false, "message", "上架异常");

        }
    }


    /**
     * 选择商品页
     */
    @RequestMapping(value = "/selectGoods", method = RequestMethod.GET)
    public String selectGoods(Model model, PageParams pageParams, HttpServletRequest request, Goods params) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());

        int type = 0;
        if (!Strings.isNullOrEmpty(request.getParameter("platformType")) && "1".equals(request.getParameter("platformType"))) {
            type = 1;
        }

        String hql = "select u from Goods u where u.status = 3 and u.isSupplier = :type  ";
        pageRequest.getParams().put("type", type);

        QueryPage<Goods> page = queryChannelService.findPage(builderSQL(hql, pageRequest.getParams(), params), pageRequest, Goods.class);

        model.addAttribute("page", page)
                .addAttribute("platformType", type)
                .addAttribute("params", params)
                .addAttribute("channels", queryChannelService.findAll("select c from GoodsChannel c where c.deleteStatus = 0 and  c.level = 1 and c.status = 1 ", GoodsChannel.class));;

        return "mall/goods/subject/goodslist";
    }


    /**
     * 选择商家页
     */
    @RequestMapping(value = "/selectMerchants", method = RequestMethod.GET)
    public String selectMerchants(Model model, PageParams pageParams) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());

        String hql = "select u from WebUser u where u.role.name = 'MERCHANT' and u.merchantCheckStatus = 2 and u.accountNonLocked = true order by u.createTime desc";
        QueryPage<WebUser> page = queryChannelService.findPage(hql, pageRequest, WebUser.class);

        model.addAttribute("page", page);

        return "mall/goods/subject/merchantslist";
    }

    /**
     * 条件筛选
     */
    private String builderSQL(String sql, Map<String, Object> params, Goods goods) {

        if (null != goods.getGoodsChannel() && goods.getGoodsChannel().getId() > 0) {
            goods.setGoodsChannel(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(goods.getGoodsChannel().getId()), GoodsChannel.class));

            sql += " and u.goodsChannel.id = :cid ";
            params.put("cid", goods.getGoodsChannel().getId());

        } else if (null != goods.getGoodsChannel() && goods.getGoodsChannel().getParent().getId() > 0) {
            goods.getGoodsChannel().setParent(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(goods.getGoodsChannel().getParent().getId()), GoodsChannel.class));

            sql += " and u.goodsChannel.parent.id = :cid ";
            params.put("cid", goods.getGoodsChannel().getParent().getId());

        } else if (null != goods.getGoodsChannel() && goods.getGoodsChannel().getParent().getParent().getId() > 0) {
            goods.getGoodsChannel().getParent().setParent(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(goods.getGoodsChannel().getParent().getParent().getId()), GoodsChannel.class));

            sql += " and u.goodsChannel.parent.parent.id = :cid ";
            params.put("cid", goods.getGoodsChannel().getParent().getParent().getId());
        }

        if (goods.getMerchant() != null && goods.getMerchant().getId() > 0) {
            sql += " and u.merchant.id = :merchantId ";
            params.put("merchantId", goods.getMerchant().getId());
        }

        if (goods.getStatus() > 0) {
            sql += " and u.status = :status ";
            params.put("status", goods.getStatus());
        } else {
            sql += " and u.status in (3,6) ";
        }

        if (!Strings.isNullOrEmpty(goods.getGoodsNo())) {
            sql += " and u.goodsNo like :goodsno ";
            params.put("goodsno", "%" + goods.getGoodsNo() + "%");
        }

        if (!Strings.isNullOrEmpty(goods.getName())) {
            sql += " and u.name like :name ";
            params.put("name", "%" + goods.getName() + "%");
        }


        if (!Strings.isNullOrEmpty(goods.getOrderByCreateTime())) {
            sql += " order by u.createTime " + goods.getOrderByCreateTime();
        } else if (!Strings.isNullOrEmpty(goods.getOrderByPrice())) {
            sql += " order by u.defaultPrice " + goods.getOrderByPrice();
        } else if (!Strings.isNullOrEmpty(goods.getOrderByStore())) {
            sql += " order by u.store " + goods.getOrderByStore();
        } else if (!Strings.isNullOrEmpty(goods.getOrderBySalesVolume())) {
            sql += " order by u.salesVolume " + goods.getOrderBySalesVolume();
        } else {
            sql += " order by u.createTime desc ";
        }

        return sql;
    }

}
